<script setup>
import {  Delete } from "@element-plus/icons-vue";
import { courseListService } from "@/api/course.js";
import { purchasePageListService, purchaseAddService, purchaseDeleteService ,purchaseBatchDeleteService,expServer,PuarchaseUploadService} from "@/api/purchase.js";
import {onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 课程数据模型
const courses = ref([]);
// 用户搜索时选中的课程id
const courseId = ref("");
// 购买列表数据模型
const purchasePageList = ref([]);

// 分页条数据模型
const pageNum = ref(1); // 当前页
const total = ref(20); // 总条数
const pageSize = ref(10); // 每页条数
const multipleSelection = ref([]);// 多选数据
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  getpurchasePageList();
};

// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  getpurchasePageList();
};

// 回显课程列表
const getcourseListService = async () => {
  let result = await courseListService();
  courses.value = result.data;
};

// 获取订单列表数据
const getpurchasePageList = async () => {
  // 设置查询参数
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    courseId: courseId.value ? courseId.value : null,
  };
  let result = await purchasePageListService(params);
  purchasePageList.value = result.data.items;
  total.value = result.data.total;
  // 扩展购买订单课程信息
  for (let i = 0; i < purchasePageList.value.length; i++) {
    let item = purchasePageList.value[i];
    for (let j = 0; j < courses.value.length; j++) {
      if (item.courseId == courses.value[j].courseId) {
        item.courseName = courses.value[j].courseName;
        break;
      }
    }
  }
};



// 控制抽屉是否显示
const visibleDrawer = ref(false);
// 添加表单数据模型
const dataModel = ref({
  id: "",
  userId: "",
  courseId: "",
  createTime: ""
});

const showAddDialog = () => {
  visibleDrawer.value = true;
  dataModel.value = {};
};

// 发送添加订单
const purchaseAdd = async () => {
  ElMessage.success(dataModel.value.courseId);

  let result = await purchaseAddService(dataModel.value);
  // 弹窗提示
  ElMessage.success(result.message ? result.message : "添加成功");
  visibleDrawer.value = false;
  // 清空添加数据
  dataModel.value = {};
  // 刷新列表
  getpurchasePageList();
};

// 发送删除订单信息
const purchaseDelete = async (row) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      let result = await purchaseDeleteService(row.id);
      ElMessage.success(result.msg ? result.msg : "删除成功");
      getpurchasePageList();
    })
    .catch(() => {});
};

// 文件输入框引用
const dialogVisible = ref(false);
const inputFile = ref();

// 触发文件选择对话框
const handleImportClick = () => {
  dialogVisible.value = true;
};

// 处理文件选择
const handleFileChange = (file, fileList) => {
  if (fileList.length > 1) {
    fileList.shift(); // 移除第一个文件，保留最新的文件
  }
  inputFile.value = fileList;
};

// 上传文件
const uploadFile = async () => {
  if (inputFile.value.length === 0) {
    ElMessage.warning("请选择一个文件");
    return;
  }

  const file = inputFile.value[0].raw;
  try {
    let result = await PuarchaseUploadService(file);
    ElMessage.success(result.message ? result.message : "上传成功");
    dialogVisible.value = false;
    getpurchasePageList();
  } catch (error) {
    ElMessage.error("上传失败: " + error.message);
  }
};

const delBatch = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }

  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      let result = await purchaseBatchDeleteService(multipleSelection.value);
      ElMessage.success(result.msg ? result.msg : "删除成功");
      getpurchasePageList();
    })
    .catch(() => {});
};
//导出报表函数
const exp = async () => {
  let result = await expServer();
  ElMessage.success(result.msg ? result.msg : "下载成功");
}

onMounted(() =>{
  getcourseListService();
  getpurchasePageList();
})

</script>

<template>
  <el-card class="page-container transparent-card">
    <template #header>
      <div class="header">
        <div class="extra">
          <el-button type="primary" @click="showAddDialog()">添加订单</el-button>
          <el-button type="danger" @click="delBatch">批量删除</el-button>
          <el-button type="success" @click="exp()">导出报表</el-button>
          <el-button type="primary" @click="handleImportClick">导入excel</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="课程列表：">
        <el-select placeholder="请选择" v-model="courseId">
          <el-option
            v-for="c in courses"
            :key="c.courseId"
            :label="c.courseName"
            :value="c.courseId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getpurchasePageList">搜索</el-button>
        <el-button @click="courseId=''">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据列表 -->
    <el-table :data="purchasePageList" style="width: 100%" @selection-change="handleSelectionChange" ref="table" :row-key="row => row.id">
      <el-table-column  width="100" type="selection" :reserve-selection="true"> </el-table-column>
      <el-table-column label="序号" width="100" type="index"> </el-table-column>
      <el-table-column label="课程名称" prop="courseName"></el-table-column>
      <el-table-column label="用户id" prop="userId"></el-table-column>
      <el-table-column label="创建时间" prop="createTime"> </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Delete" circle plain type="danger" @click="purchaseDelete(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
    <!-- 抽屉 -->
    <el-drawer
      v-model="visibleDrawer"
      title="添加订单"
      direction="rtl"
      size="50%"
    >
      <el-form :model="dataModel" label-width="100px">
        <el-form-item label="课程">
          <el-select
            placeholder="请选择"
            v-model="dataModel.courseId"
          >
            <el-option
              v-for="c in courses"
              :key="c.courseId"
              :label="c.courseName"
              :value="c.courseId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="purchaseAdd()"
          >
            添加
          </el-button>
          <el-button type="info" @click="visibleDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 导入对话框 -->
    <el-dialog v-model="dialogVisible" title="导入Excel文件" width="30%">
      <el-upload
        ref="upload"
        action=""
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="inputFile"
        accept=".xlsx, .xls"
        :show-file-list="true"
      >
        <template #trigger>
          <el-button type="primary">选取文件</el-button>
        </template>
        <el-button type="success" @click="uploadFile()">上传文件</el-button>
      </el-upload>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.transparent-card {
  background-color: rgba(255, 255, 255, 0.8); /* 半透明背景 */
  backdrop-filter: blur(10px); /* 模糊效果 */
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 可选：轻微阴影效果 */
}
.el-select {
  width: 200px;
}
/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>